<?php

namespace App\Http\Requests\Admin;

use App\Http\Models\App\App;
use App\Http\Models\App\AppAuth;
use App\Http\Models\App\AppGroup;
use App\Http\Models\App\AppGroupAuthRelation;
use App\Http\Requests\Common\BaseRequest as Request;

class AppRequest extends Request
{
    //
    public function app()
    {
        $keys = ['rows', 'type', 'page', 'sort', 'order', 'name', 'host', 'status'];
        $data = $this->only($keys);
        if ($data['type'] == 'ajax') {
            $model = App::where(function ($query) use ($data) {
                if ($data['name']) {
                    $query->where('name', 'like', "%{$data['name']}%");
                }
                if ($data['host']) {
                    $query->where('host', 'like',"%{$data['host']}%");
                }
                if ($data['status']) {
                    $status = $data['status'] == 2 ? 0 : $data['status'];
                    $query->where('status', $status);
                }
            });
            $apps = $model->orderBy($data['sort'], $data['order'])->paginate($data['rows']);
            $data   = [
                'total' => $apps->total(),
                'rows'  => $apps->getCollection(),
            ];
            return \Response::json($data);
        }
        return View('admin.app.app');
    }
    //
    public function app_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "name"   => "required|min:2|max:20|unique:app",
            "host"   => "required|min:2|max:20|unique:app",
            "key"    => "required|min:2|max:80",
            "secret" => "required|min:2|max:80",
            "desc"   => "required|min:2|max:80",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "name"   => "应用名称",
            "key"    => "应用签名",
            "secret" => "应用秘钥",
            "desc"   => "应用描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //数据入库
        $clean = [
            'name'          => $data['name'],
            'host'          => $data['host'],
            'key'           => $data['key'],
            'secret'        => mb_substr(md5($data['secret']), rand(1, 20), 10, 'utf-8'),
            'desc'          => $data['desc'],
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        if (!App::insert($clean)) {
            return self::_json([], -1, '新增失败!');
        }
        return self::_json();
    }
    //
    public function app_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"     => "required|exists:app",
            "name"   => "required|min:2|max:20",
            "host"   => "required|min:2|max:20",
            "key"    => "required|min:2|max:80",
            "desc"   => "required|min:2|max:80",
            "secret" => "",
            "status" => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "id"     => "应用ID",
            "name"   => "应用名称",
            "key"    => "应用签名",
            "secret" => "应用秘钥",
            "desc"   => "应用描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查应用名称+应用域名是否重复
        $_id = App::where('name', $data['name'])->orWhere('host', $data['host'])->pluck('id');
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '名称或域名重复');
        }
        //更新数据
        $clean = [
            'name'          => $data['name'],
            'host'          => $data['host'],
            'key'           => $data['key'],
            'desc'          => $data['desc'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        //判断是否更新秘钥
        $data['secret'] ? $clean['secret'] = mb_substr(md5($data['secret']), rand(1, 20), 10, 'utf-8') : '';

        if (!App::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新失败!');
        }
        return self::_json();
    }
    //
    public function auth()
    {
        $keys = ['type', 'style', 'app_id', 'auth_id', 'parent_id', 'name', 'status'];
        extract($this->only($keys));
        if ($type == 'ajax') {
            $model = \DB::connection('cas')->table('app_auth');
            if ($app_id) {
                $model->where('app_id', $app_id);
            }
            //编辑
            if ($auth_id) {
                $model->where('id', '!=', $auth_id);
            }
            //新增
            if ($parent_id || $parent_id === "0") {
                $model->where('parent_id', '!=', intval($parent_id));
            }
            if ($name) {
                $model->where('name', 'like', "%{$name}%");
            }
            if ($status) {
                $status = $status == 2 ? 0 : $status;
                $model->where('status', $status);
            }
            $auths = $model->orderBy('app_id', 'asc')->orderBy('weight', 'desc')->get();
            $tree  = array_map('get_object_vars', $auths);
            $total = count($tree);
            $rows  = $this->getTree($tree, 0);
            $data  = [
                'total' => $total,
                'rows'  => $rows,
            ];
            return $style == 'tree' ? \Response::json($rows) : \Response::json($data);
        }
        //
        $records = App::get();
        $apps    = is_null($records) ? [] : $records->toArray();
        $data    = [
            'apps'   => $apps,
            'app_id' => intval($app_id),
        ];
        return View('admin.app.auth', compact('data'));
    }
    //
    public function auth_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "name"      => "required|min:2|max:20",
            "parent_id" => "",
            "app_id"    => "required",
            "uri"       => "",
            "css"       => "",
            "desc"      => "required|min:2|max:180",
            "is_show"   => "",
            "status"    => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "app_id" => "应用ID",
            "name"   => "应用名称",
            "desc"   => "应用描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //数据入库
        $clean = [
            'name'          => $data['name'],
            'parent_id'     => $data['parent_id'],
            'app_id'        => $data['app_id'],
            'uri'           => $data['uri'],
            'css'           => $data['css'],
            'desc'          => $data['desc'],
            'is_show'       => 1,
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        if (!AppAuth::insert($clean)) {
            return self::_json([], -1, '新增失败!');
        }
        return self::_json();
    }
    //
    public function auth_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"        => "required|exists:app_auth",
            "name"      => "required|min:2|max:20",
            "parent_id" => "",
            "app_id"    => "required",
            "uri"       => "",
            "css"       => "",
            "desc"      => "required|min:2|max:180",
            "is_show"   => "",
            "status"    => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
        );
        $attributes = array(
            "id"     => "权限ID",
            "app_id" => "应用ID",
            "name"   => "应用名称",
            "desc"   => "应用描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查应用名称+应用域名是否重复
        $_id = AppAuth::where('name', $data['name'])->where('uri', $data['uri'])->where('parent_id', $data['parent_id'])->pluck('id');
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '该App的权限重复');
        }
        //更新数据
        $clean = [
            'name'          => $data['name'],
            'parent_id'     => $data['parent_id'],
            'app_id'        => $data['app_id'],
            'uri'           => $data['uri'],
            'css'           => $data['css'],
            'desc'          => $data['desc'],
            'is_show'       => $data['is_show'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        if (!AppAuth::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新失败!');
        }
        return self::_json();
    }
    //
    public function group()
    {
        $keys = ['rows', 'type', 'page', 'sort', 'order', 'name', 'app_id', 'status'];
        $data = $this->only($keys);
        if ($data['type'] == 'ajax') {
            $model = AppGroup::where(function ($query) use ($data) {
                if ($data['name']) {
                    $query->where('name', 'like', "%{$data['name']}%");
                }
                if ($data['app_id']) {
                    $query->where('app_id', $data['app_id']);
                }
                if ($data['status']) {
                    $status = $data['status'] == 2 ? 0 : $data['status'];
                    $query->where('status', $status);
                }
            });
            //
            $groups = $model->orderBy($data['sort'], $data['order'])->paginate($data['rows']);
            $data   = [
                'total' => $groups->total(),
                'rows'  => $groups->getCollection(),
            ];
            return \Response::json($data);
        }
        //
        $apps = self::_toArray(App::where('status', 1)->get());
        //构造key-value数据
        $appArr = [];
        foreach ($apps as $app) {
            $appArr[$app['id']] = $app['name'];
        }
        $data = [
            'apps'    => $apps,
            'appJson' => json_encode($appArr),
            'app_id'  => intval($data['app_id']),
        ];
        return View('admin.app.group', compact('data'));
    }
    //
    public function group_auth()
    {
        $auth_ids = [];
        $input    = $this->only(['group_id']);
        if (!$input['group_id']) {
            return \Response::json($auth_ids);
        }
        foreach (AppGroup::find($input['group_id'])->hasManyAuth as $auth) {
            if ($auth->status == 1) {
                $auth_ids[] = $auth->auth_id;
            }
        }
        return \Response::json($auth_ids);
    }
    //
    public function group_add()
    {
        //动态验证发送过来的数据
        $rules = [
            "name"    => "required|min:2|max:20|unique:app_group",
            "app_id"  => "required|exists:app,id",
            "auth_id" => "",
            "desc"    => "required|min:2|max:180",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已存在",
        );
        $attributes = array(
            "app_id" => "应用ID",
            "name"   => "分组名称",
            "desc"   => "分组描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //分组数据入库
        $clean = [
            'name'          => $data['name'],
            'app_id'        => $data['app_id'],
            'desc'          => $data['desc'],
            'status'        => 1,
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'created_at'    => date('Y-m-d H:i:s'),
        ];
        //新增组信息
        $insert_id = AppGroup::insertGetId($clean);
        if (!$insert_id) {
            return self::_json([], -1, '新增失败!');
        }
        //获取传递过来的auth_id
        $auth_ids = $data['auth_id'] ? $data['auth_id'] : [];
        //根据auth_id获取parent_id
        $parent_ids = self::_toArray(AppAuth::whereIn('id', $auth_ids)->select('id', 'parent_id')->get());
        //合并auth_id和parent_id
        $total_ids = [];
        array_map(function ($v) use (&$total_ids) {
            $total_ids[$v['id']] = $v['id'];
            if ($v['parent_id']) {
                $total_ids[$v['parent_id']] = $v['parent_id'];
            }
        }, $parent_ids);
        //
        foreach ($total_ids as $auth_id) {
            $clean = [
                'group_id'      => $insert_id,
                'auth_id'       => $auth_id,
                'status'        => 1,
                'operator_id'   => $this->admin['id'],
                'operator_name' => $this->admin['name'],
                'created_at'    => date('Y-m-d H:i:s'),
                'deleted_at'    => '',
            ];
            if (!AppGroupAuthRelation::insert($clean)) {
                return self::_json([], -1, '新增关联权限数据失败!');
            }
        }
        return self::_json();
    }
    //
    public function group_edit()
    {
        //动态验证发送过来的数据
        $rules = [
            "id"      => "required|exists:app_group",
            "name"    => "required|min:2|max:20",
            "app_id"  => "required|exists:app,id",
            "auth_id" => "",
            "desc"    => "required|min:2|max:180",
            "status"  => "",
            "type"    => "",
        ];
        $message = array(
            "required" => ":attribute不能为空",
            "min"      => ":attribute长度必能少于:min",
            "max"      => ":attribute长度不能大于:max",
            "unique"   => ":attribute已经存在",
            "exists"   => ":attribute不存在",
        );
        $attributes = array(
            "id"     => "权限ID",
            "app_id" => "应用ID",
            "name"   => "应用名称",
            "desc"   => "应用描述",
        );
        //
        $data  = $this->only(array_keys($rules));
        $check = \Validator::make($data, $rules, $message, $attributes);
        $error = $check->messages()->first();
        if ($error) {
            return self::_json([], 1, $error);
        }
        //检查分组名称是否重复
        $_id = AppGroup::where('name', $data['name'])->where('app_id', $data['app_id'])->pluck('id');
        if (isset($_id) && ($data['id'] != $_id)) {
            return self::_json([], 1, '该分组名称重复');
        }
        //更新分组数据
        $clean = [
            'name'          => $data['name'],
            'app_id'        => $data['app_id'],
            'desc'          => $data['desc'],
            'status'        => $data['status'],
            'operator_id'   => $this->admin['id'],
            'operator_name' => $this->admin['name'],
            'updated_at'    => date('Y-m-d H:i:s'),
        ];
        if (!AppGroup::where('id', $data['id'])->update($clean)) {
            return self::_json([], -1, '更新分组失败!');
        }
        //启用|禁用
        if ($data['type'] == 'modify') {
            return self::_json();
        }
        //////////////////////////////////////////////////
        ##########把现在已经存在的关联状态改为禁用########
        ##########更新或者新增重新关联的权限##############
        ###防止app_id父级权限缺失,把appid的父级权限补上###
        //////////////////////////////////////////////////
        AppGroupAuthRelation::where('group_id', $data['id'])->update(['status' => 0, 'updated_at' => date('Y-m-d H:i:s')]);
        //获取传递过来的auth_id
        $auth_ids = $data['auth_id'] ? $data['auth_id'] : [];
        //根据auth_id获取parent_id
        $parent_ids = self::_toArray(AppAuth::whereIn('id', $auth_ids)->select('id', 'parent_id')->get());
        //合并auth_id和parent_id
        $total_ids = [];
        array_map(function ($v) use (&$total_ids) {
            $total_ids[$v['id']] = $v['id'];
            if ($v['parent_id']) {
                $total_ids[$v['parent_id']] = $v['parent_id'];
            }
        }, $parent_ids);
        //
        foreach ($total_ids as $auth_id) {
            $_id = AppGroupAuthRelation::where('auth_id', $auth_id)->where('group_id', $data['id'])->pluck('id');
            //update
            if ($_id) {
                if (!AppGroupAuthRelation::where('id', $_id)->update(['status' => 1, 'updated_at' => date('Y-m-d H:i:s')])) {
                    return self::_json([], -1, '更新关联权限数据失败!');
                }
            } else {
                $clean = [
                    'group_id'      => $data['id'],
                    'auth_id'       => $auth_id,
                    'status'        => 1,
                    'operator_id'   => $this->admin['id'],
                    'operator_name' => $this->admin['name'],
                    'created_at'    => date('Y-m-d H:i:s'),
                    'deleted_at'    => '',
                ];
                if (!AppGroupAuthRelation::insert($clean)) {
                    return self::_json([], -1, '新增关联权限数据失败!');
                }
            }
        }
        return self::_json();
    }
    //
    public function getTree($data, $pId)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $pId) {
                $v['children'] = $this->getTree($data, $v['id']);
                $v['text']     = $v['name'];
                $tree[]        = $v;
            }
        }
        return $tree;
    }
}
